
use crate::conf_parse::ast::Ast;
use crate::conf_parse::status::Status;
use std::collections::VecDeque;
use crate::idata::cont::IVec;

#[derive(Clone, Debug)]
pub struct MultiExpr(pub Vec<Expression>);

#[derive(Clone, Debug)]
pub enum Atom{
    Literal(String),
    LiteralList(Vec<String>),
    Dot,
}
#[derive(Clone, Debug)]
pub struct RepInfo{
    pub expression: Box<Expression>,
    pub min: Option<usize>,
    pub max: Option<usize>,
    pub end: Option<Box<Expression>>,
}

impl RepInfo{
    pub fn new(expression: Box<Expression>, min: Option<usize>,
               max: Option<usize>, end: Option<Box<Expression>>)
               ->RepInfo{
        return RepInfo{
            expression: expression,
            min: min,
            max: max,
            end: end,
        };
    }
}
#[derive(Clone,Debug)]
pub struct NestedInfo{
    pub expression: Box<Expression>,
    pub left: Box<Expression>,
    pub right: Box<Expression>,
    pub and: Box<Expression>,
    pub or: Box<Expression>,
}
#[derive(Clone,Debug)]
pub struct ConnectInfo{
    //base conn base conn base，以base表达式开始，以base表达式结束，中间以conn表达式连接。
    pub base: Box<Expression>,
    pub conn: Box<Expression>,
    pub space: Box<Expression>,
}

#[derive(Clone, Debug)]
pub enum Expression{
    Atom(Atom),
    And(MultiExpr),
    Or(MultiExpr),
    Not(Box<Expression>),
    Repeat(RepInfo),
    SubRule((String,Box<Expression>)),
}

pub enum FilterExpression{
    And(Box<FilterExpression>,Box<FilterExpression>),
    Or(Box<FilterExpression>,Box<FilterExpression>),
    Expr(Expression)
}

#[derive(Debug,Clone)]
pub enum FilterAst{
    And(Box<FilterAst>,Box<FilterAst>),
    Or(Box<FilterAst>,Box<FilterAst>),
    Expr(Vec<Ast>)
}

#[derive(Debug,Clone)]
pub struct ConnAst{
    pub list: VecDeque<Vec<Ast>>,
}
pub enum ConnReturn<'a>{
    Ok((Status<'a>, ConnAst)),
    Err((Status<'a>, String)),
}

pub enum ParseReturn<'a>{
    Ok((Status<'a>, Vec<Ast>)),
    Err(Status<'a>),
}

pub enum FilterReturn<'a>{
    Ok((Status<'a>, FilterAst)),
    Err((Status<'a>, String)),
}

fn parse_dot<'a,'b>(mut status: Status<'a>, location: &'b mut usize, debug: bool)->ParseReturn<'a>{
    if let Some(tmp_char) = status.get_char() {
        *location += 1;
        if debug{
            println!("parse_dot, get [{}] chars [{:?}]", tmp_char, status.chars);
        }
        return ParseReturn::Ok((status, vec![Ast::Value(tmp_char.to_string())]));
    }else{
        if debug{
            println!("parse_dot, get none chars [{:?}]", status.chars);
        }
        return ParseReturn::Err(status);
    }
}
fn parse_char<'a,'c>(status: &'a mut Status, ch: char, location: &'c mut usize, debug: bool)->Option<char>{
    let tmp_char = status.get_char()?;

    if tmp_char == ch{
        *location += 1;
        return Some(ch);
    }else{
        status.possion_bak(1);
        return None;
    }
}
pub fn parse_literal<'a,'b,'c>(mut status: Status<'a>, literal: &'b str, location: &'c mut usize, debug: bool)
        ->ParseReturn<'a>{

    let mut tmp = 0;
    for ch in literal.chars(){
        if let None = parse_char(&mut status, ch, &mut tmp, debug){
            status.possion_bak(tmp);
            if debug{
                println!("parse_literal, literal [{}] none chars [{:?}]", literal, status.chars);
            }
            return ParseReturn::Err(status);
        }
    }

    if debug{
        println!("parse_literal, literal [{}] get chars [{:?}]", literal, status.chars);
    }
    *location += tmp;
    return ParseReturn::Ok((status, vec![Ast::Value(literal.to_string())]));
}
pub fn parse_literal_list<'a,'b,'c>(mut status: Status<'a>, literal_list: &'b Vec<String>,
                              location: &'c mut usize, debug: bool)->ParseReturn<'a>{

    let mut in_list = false;
    let mut bak_literal = "".to_string();

    for literal in literal_list.iter() {
        let mut checked = true;
        let mut tmp = 0;

        for ch in literal.chars() {
            if let None = parse_char(&mut status, ch, &mut tmp, debug) {
                status.possion_bak(tmp);
                checked = false;
                break;
            }
        }

        if checked{
            *location += tmp;
            in_list = true;
            bak_literal = literal.clone();
            break;
        }
    }

    if in_list{
        if debug{
            println!("parse_literal_list, literal_list [{:?}] get chars [{:?}]", literal_list, status.chars);
        }
        return ParseReturn::Ok((status, vec![Ast::Value(bak_literal)]));
    }else{
        if debug{
            println!("parse_literal, literal_list [{:?}] get chars [{:?}]", literal_list, status.chars);
        }
        return ParseReturn::Err(status);
    }
}

pub fn parse_atom<'a,'b, 'c>(status: Status<'a>, atom: &'b Atom, location: &'c mut usize, debug: bool)
        ->ParseReturn<'a>{
    match atom{
        Atom::Literal(ref val) => {parse_literal(status, val, location, debug)},
        Atom::LiteralList(ref val) => {parse_literal_list(status, val, location, debug)},
        Atom::Dot => {parse_dot(status, location, debug)},
    }
}

pub fn parse<'a,'b:'a>(status: Status<'a>, expr: &'b Expression, debug: bool) -> Result<(Status<'a>, Ast), Status<'a>>{

    let mut location = 0;

    match parse_expr(status.clone(), expr, &mut location, debug){
        ParseReturn::Ok((st,nodes)) => {
            return Ok((st, Ast::Rule(("root".to_string(), nodes))));
        },
        ParseReturn::Err(st) => {
            return Err(st);
        },
    }
}

fn parse_expr<'a,'b,'c>(status: Status<'a>, expression: &'b Expression, location: &'c mut usize, debug: bool)
        ->ParseReturn<'a>{
    match *expression{
        Expression::Atom(ref val) => {parse_atom_as_expr(status, &val, location, debug)},
        Expression::And(ref val) => {parse_and(status, &val, location, debug)},
        Expression::Or(ref val) => {parse_or(status, &val, location, debug)},
        Expression::Not(ref val) => {parse_not(status, &val, location, debug)},
        Expression::Repeat(ref val) => {parse_repeat(status, &val, location, debug)},
        Expression::SubRule((ref k,ref v)) => {
            parse_sub_rule(status, k, v, location, debug)
        },
    }
}
enum TailCall<T,R>{
    Call(T),
    Return(R),
}
fn tail_call<T,R,F>(seed: T, mut f: F)->R
    where
        F: FnMut(T)->TailCall<T,R>,
{
    let mut status = TailCall::Call(seed);
    loop{
        match status{
            TailCall::Call(arg) => {
                status = f(arg);
            },
            TailCall::Return(r) => {
                return r;
            }
        }
    }
}
fn parse_sub_rule<'a,'b,'c>(status: Status<'a>, sub_rule_name: &'b str, sub_rule: &'b Box<Expression>, location: &'c mut usize, debug: bool)
        ->ParseReturn<'a>{

    match parse_expr(status, sub_rule, location, debug){
        ParseReturn::Ok((st, nodes)) => {
            return ParseReturn::Ok((st, vec![Ast::Rule((sub_rule_name.to_string(), nodes))]));
        },
        ParseReturn::Err(st) => {
            return ParseReturn::Err(st);
        }
    }
}
fn parse_and<'a,'b,'c>(status: Status<'a>, multi_expr: &'b MultiExpr, location: &'c mut usize, debug: bool)
        ->ParseReturn<'a>{
    let init: (Status, &[Expression], Vec<Ast>, usize, bool) = (status, &(multi_expr.0), vec![], 0, debug);

    if debug{
        println!("parse_and, and_list [{:?}] chars [{:?}]", multi_expr, init.0.chars);
    }

    tail_call(init, |mut rp|{
        if rp.1.is_empty(){
            *location += rp.3;
            return TailCall::Return(ParseReturn::Ok((rp.0, rp.2)));
        }else{
            match parse_expr(rp.0, &rp.1[0], &mut rp.3, rp.4) {
                ParseReturn::Ok((st, nodes)) => {
                    if debug{
                        println!("parse_and, and_one [{:?}] ok chars [{:?}]", &rp.1[0], st.chars);
                    }
                    TailCall::Call((st, &rp.1[1..], rp.2.iappend(nodes), rp.3, rp.4))
                },
                ParseReturn::Err(mut st) => {
                    if debug{
                        println!("parse_and, and_one [{:?}] none chars [{:?}]", &rp.1[0], st.chars);
                    }
                    st.possion_bak(rp.3);
                    TailCall::Return(ParseReturn::Err(st))
                },
            }
        }
    })
}
//{{a and b} and {c and d}} or e
// a and b
//{a}
//{a and b}
#[derive(Debug)]
enum NestedType{
    Left,
    SingleAst(FilterAst),//已经合并了的独立表达式
    And,
    AndWait(FilterAst),//独立表达式+and
    Or,
    OrWait(FilterAst),//独立表达式+or
    Right,
}
fn nested_type_merge(nested_list: &mut VecDeque<NestedType>, new: NestedType,
    debug: bool)->Option<String>{

    if debug{
        println!("nested_merge, new: [{:?}]", new);
        println!("             list: [{:?}]", nested_list);
    }
    if let Some(pre) = nested_list.pop_back(){
        match &new{
            NestedType::Left => {
                match &pre{
                    NestedType::Left => {
                        //{ {
                        nested_list.push_back(pre);
                        nested_list.push_back(new);
                        return None;
                    },
                    NestedType::SingleAst(ref pre_ast) => {
                        //a {
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::And => {
                        //and {
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::AndWait(ref pre_ast) => {
                        //a and {
                        nested_list.push_back(pre);
                        nested_list.push_back(new);
                        return None;
                    },
                    NestedType::Or => {
                        //or {
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::OrWait(ref pre_ast) => {
                        //a or {
                        nested_list.push_back(pre);
                        nested_list.push_back(new);
                        return None;
                    },
                    NestedType::Right => {
                        //} {
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                }
            },
            NestedType::SingleAst(new_ast) => {
                match &pre{
                    NestedType::Left => {
                        //{ a
                        nested_list.push_back(pre);
                        nested_list.push_back(new);
                        return None;
                    },
                    NestedType::SingleAst(ref pre_ast) => {
                        //a b
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::And => {
                        //and a
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::AndWait(pre_ast) => {
                        //a and b
                        let new = NestedType::SingleAst(FilterAst::And(Box::new(pre_ast.clone()),Box::new(new_ast.clone())));
                        return nested_type_merge(nested_list, new, debug);
                    },
                    NestedType::Or => {
                        //or a
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::OrWait(pre_ast) => {
                        //a or b
                        let new = NestedType::SingleAst(FilterAst::Or(Box::new(pre_ast.clone()),Box::new(new_ast.clone())));
                        return nested_type_merge(nested_list, new, debug);
                    },
                    NestedType::Right => {
                        //} a
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                }
            },
            NestedType::And => {
                match &pre{
                    NestedType::Left => {
                        //{ and
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::SingleAst(pre_ast) => {
                        //a and
                        let new = NestedType::AndWait(pre_ast.clone());
                        return nested_type_merge(nested_list, new, debug);
                    },
                    NestedType::And => {
                        //and and
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::AndWait(_pre_ast) => {
                        //a and and
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::Or => {
                        //or and
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::OrWait(_pre_ast) => {
                        //a or and
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::Right => {
                        //} and
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                }
            },
            NestedType::AndWait(_new_ast) => {
                match &pre{
                    NestedType::Left => {
                        //{ a and
                        nested_list.push_back(pre);
                        nested_list.push_back(new);
                        return None;
                    },
                    NestedType::SingleAst(_pre_ast) => {
                        //a a and
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::And => {
                        //and a and
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::AndWait(_pre_ast) => {
                        //a and a and
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::Or => {
                        //or a and
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::OrWait(_pre_ast) => {
                        //a or a and
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::Right => {
                        //} a and
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                }
            },
            NestedType::Or => {
                match &pre{
                    NestedType::Left => {
                        //{ or
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::SingleAst(pre_ast) => {
                        //a or
                        let new = NestedType::OrWait(pre_ast.clone());
                        return nested_type_merge(nested_list, new, debug);
                    },
                    NestedType::And => {
                        //and or
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::AndWait(_pre_ast) => {
                        //a and or
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::Or => {
                        //or or
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::OrWait(_pre_ast) => {
                        //a or or
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::Right => {
                        //} or
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                }
            },
            NestedType::OrWait(new_ast) => {
                match &pre{
                    NestedType::Left => {
                        //{ a or
                        nested_list.push_back(pre);
                        nested_list.push_back(new);
                        return None;
                    },
                    NestedType::SingleAst(pre_ast) => {
                        //a a or
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::And => {
                        //and a or
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::AndWait(_pre_ast) => {
                        //a and a or
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::Or => {
                        //or a or
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::OrWait(_pre_ast) => {
                        //a or a or
                        return Some(format!("[{:?}] after [{:?}]", new,pre));
                    },
                    NestedType::Right => {
                        //} a or
                        return Some(format!("[{:?}] after Right", new_ast));
                    },
                }
            },
            NestedType::Right => {
                match &pre {
                    NestedType::Left => {
                        //{ }
                        return Some(format!("[{:?}] after [{:?}]", new, pre));
                    },
                    NestedType::SingleAst(pre_ast) => {
                        //a }
                        if let Some(ppre) = nested_list.pop_back(){
                            match &ppre{
                                NestedType::Left => {
                                    //{ a }
                                    let new = NestedType::SingleAst(pre_ast.clone());
                                    return nested_type_merge(nested_list,new, debug);
                                },
                                NestedType::SingleAst(_ppre_ast) => {
                                    //a a }
                                    return Some(format!("[{:?}] after [{:?}] after [{:?}]", new, pre,ppre));
                                },
                                NestedType::And => {
                                    //and a }
                                    return Some(format!("[{:?}] after [{:?}] after [{:?}]", new, pre,ppre));
                                },
                                NestedType::AndWait(_ppre_ast) => {
                                    //a and a a }
                                    return Some(format!("[{:?}] after [{:?}] after [{:?}]", new, pre,ppre));
                                },
                                NestedType::Or => {
                                    //or a }
                                    return Some(format!("[{:?}] after [{:?}] after [{:?}]", new, pre,ppre));
                                },
                                NestedType::OrWait(_ppre_ast) => {
                                    //a or a }
                                    return Some(format!("[{:?}] after [{:?}] after [{:?}]", new, pre,ppre));
                                },
                                NestedType::Right => {
                                    //} a }
                                    return Some(format!("[{:?}] after [{:?}] after [{:?}]", new, pre,ppre));
                                },
                            }
                        }else{
                            return Some(format!("[{:?}] after [{:?}] after none", new, pre));
                        }
                    },
                    NestedType::And => {
                        //and }
                        return Some(format!("[{:?}] after [{:?}]", new, pre));
                    },
                    NestedType::AndWait(_pre_ast) => {
                        //a and }
                        return Some(format!("[{:?}] after [{:?}]", new, pre));
                    },
                    NestedType::Or => {
                        //or }
                        return Some(format!("[{:?}] after [{:?}]", new, pre));
                    },
                    NestedType::OrWait(_pre_ast) => {
                        //a or }
                        return Some(format!("[{:?}] after [{:?}]", new, pre));
                    },
                    NestedType::Right => {
                        //} }
                        return Some(format!("[{:?}] after Right", new));
                    },
                }
            },
        }
    }else{
        nested_list.push_back(new);
        return None;
    }
}
pub fn parse_connect<'a>(status: Status<'a>, conn_info: ConnectInfo, location: &mut usize, debug: bool)
    ->ConnReturn<'a>{

    let init: (Status, ConnectInfo, usize, bool, VecDeque<Vec<Ast>>, usize) =
        (status, conn_info, 0, debug, VecDeque::new(), 0);

    tail_call(init, |mut rp| {
        if rp.5 == 0{
            //wait base
            if let ParseReturn::Ok((st, ast)) = parse_expr(rp.0.clone(), &rp.1.base,
                    &mut rp.2, rp.3){
                rp.4.push_back(ast);
                if st.desc.len() == st.pos.n{
                    //parse to the end
                    TailCall::Return(ConnReturn::Ok((st,ConnAst{list: rp.4})))
                }else{
                    rp.5 = 1;
                    TailCall::Call((st,rp.1,rp.2,rp.3,rp.4,rp.5))
                }
            }else{
                let err_desc = format!("[{:?}] wait base failed, chars [{:?}]", rp.4, rp.0.chars);
                rp.0.possion_bak(rp.2);
                TailCall::Return(ConnReturn::Err((rp.0.clone(), err_desc)))
            }
        }else if rp.5 == 1{
            //wait space
            if let ParseReturn::Ok((st, ast)) = parse_expr(rp.0.clone(), &rp.1.space,
                                                           &mut rp.2, rp.3){
                rp.4.push_back(ast);
                rp.5 = 2;
                TailCall::Call((st,rp.1,rp.2,rp.3,rp.4,rp.5))
            }else{
                let err_desc = format!("[{:?}] wait space after base failed [{:?}]", rp.4, rp.0.chars);
                rp.0.possion_bak(rp.2);
                TailCall::Return(ConnReturn::Err((rp.0.clone(), err_desc)))
            }
        }else if rp.5 == 2{
            //wait conn
            if let ParseReturn::Ok((st, ast)) = parse_expr(rp.0.clone(), &rp.1.conn,
                                                           &mut rp.2, rp.3){
                rp.4.push_back(ast);
                rp.5 = 3;
                TailCall::Call((st,rp.1,rp.2,rp.3,rp.4,rp.5))
            }else{
                let err_desc = format!("[{:?}] wait conn failed [{:?}]", rp.4, rp.0.chars);
                rp.0.possion_bak(rp.2);
                TailCall::Return(ConnReturn::Err((rp.0.clone(), err_desc)))
            }
        }else if rp.5 == 3{
            //wait space
            if let ParseReturn::Ok((st, ast)) = parse_expr(rp.0.clone(), &rp.1.space,
                                                           &mut rp.2, rp.3){
                rp.4.push_back(ast);
                rp.5 = 0;
                TailCall::Call((st,rp.1,rp.2,rp.3,rp.4,rp.5))
            }else{
                let err_desc = format!("[{:?}] wait space after conn failed [{:?}]", rp.4, rp.0.chars);
                rp.0.possion_bak(rp.2);
                TailCall::Return(ConnReturn::Err((rp.0.clone(), err_desc)))
            }
        }else{
            let err_desc = format!("[{:?}] connect wait err {}", rp.4 , rp.5);
            rp.0.possion_bak(rp.2);
            TailCall::Return(ConnReturn::Err((rp.0.clone(), err_desc)))
        }
    })

}
pub fn parse_nested<'a>(status: Status<'a>, nested_info: NestedInfo, location: &mut usize, debug: bool)
    ->FilterReturn<'a>{

    let init: (Status, NestedInfo, usize, bool, VecDeque<NestedType>) = (status, nested_info, 0, debug, VecDeque::new());

    tail_call(init, |mut rp|{

        if let ParseReturn::Ok((st, _)) = parse_expr(rp.0.clone(), &rp.1.left, &mut rp.2, rp.3){
            //left
            if debug{
                println!("parse_nested left chars [{:?}]", st.chars);
            }
            if let Some(err) = nested_type_merge(&mut rp.4,NestedType::Left, debug){
                TailCall::Return(FilterReturn::Err((st,err)))
            }else{
                TailCall::Call((st,rp.1,rp.2,rp.3,rp.4))
            }
        }else if let ParseReturn::Ok((st, ast)) = parse_expr(rp.0.clone(), &rp.1.right, &mut rp.2, rp.3){
            //right
            if debug{
                println!("parse_nested right chars [{:?}]", st.chars);
            }
            if let Some(err) = nested_type_merge(&mut rp.4,NestedType::Right, debug){
                TailCall::Return(FilterReturn::Err((st,err)))
            }else{
                TailCall::Call((st,rp.1,rp.2,rp.3,rp.4))
            }
        }else if let ParseReturn::Ok((st, ast)) = parse_expr(rp.0.clone(), &rp.1.and, &mut rp.2, rp.3){
            //and
            if debug{
                println!("parse_nested and chars [{:?}]", st.chars);
            }
            if let Some(err) = nested_type_merge(&mut rp.4,NestedType::And, debug){
                TailCall::Return(FilterReturn::Err((st,err)))
            }else{
                TailCall::Call((st,rp.1,rp.2,rp.3,rp.4))
            }
        }else if let ParseReturn::Ok((st, ast)) = parse_expr(rp.0.clone(), &rp.1.or, &mut rp.2, rp.3){
            //or
            if debug{
                println!("parse_nested or chars [{:?}]", st.chars);
            }
            if let Some(err) = nested_type_merge(&mut rp.4,NestedType::Or, debug){
                TailCall::Return(FilterReturn::Err((st,err)))
            }else{
                TailCall::Call((st,rp.1,rp.2,rp.3,rp.4))
            }
        }else if let ParseReturn::Ok((st, ast)) = parse_expr(rp.0.clone(), &rp.1.expression, &mut rp.2, rp.3){
            //expression
            if debug{
                println!("parse_nested expr chars [{:?}]", st.chars);
            }
            if let Some(err) = nested_type_merge(&mut rp.4, NestedType::SingleAst(FilterAst::Expr(ast)), debug){
                TailCall::Return(FilterReturn::Err((st,err)))
            }else{
                TailCall::Call((st,rp.1,rp.2,rp.3,rp.4))
            }
        }else {
            if debug{
                println!("parse_nested end ast [{:?}] chars [{:?}]", rp.4, rp.0.chars);
            }
            if rp.0.desc.len() != rp.0.pos.n{
                let errdesc = format!("parse not end [{:?}]", rp.0.chars);
                TailCall::Return(FilterReturn::Err((rp.0, errdesc)))
            }else{
                if rp.4.len() != 1{
                    TailCall::Return(FilterReturn::Err((rp.0,
                    format!("parse VecDeque<NestedType>.len() != 1, [{:?}]", rp.4))))
                }else{
                    if let Some(ast) = rp.4.pop_back(){
                        match ast{
                            NestedType::SingleAst(ast) => {
                                TailCall::Return(FilterReturn::Ok((rp.0, ast)))
                            },
                            _ => {
                                TailCall::Return(FilterReturn::Err((rp.0,
                                format!("parse return is Not SingleAst, [{:?}]", ast))))
                            },
                        }
                    }else{
                        TailCall::Return(FilterReturn::Err((rp.0,
                        format!("parse return is None"))))
                    }
                }
            }
        }
    })
}
fn parse_or<'a,'b,'c>(status: Status<'a>, multi_expr: &'b MultiExpr, location: &'c mut usize, debug: bool)
        ->ParseReturn<'a>{
    let init: (Status, &[Expression], Vec<Ast>, bool, usize) =
            (status, &(multi_expr.0), vec![], debug, 0);

    if debug{
        println!("parse_or, or_list [{:?}] chars [{:?}]", multi_expr, init.0.chars);
    }

    tail_call(init, |mut rp|{
        if rp.1.is_empty(){
            rp.0.possion_bak(rp.4);
            TailCall::Return(ParseReturn::Err(rp.0))
        }else{
            match parse_expr(rp.0.clone(), &rp.1[0], &mut rp.4, rp.3) {
                ParseReturn::Ok((st, nodes)) => {
                    if debug{
                        println!("parse_or, or_one [{:?}] ok chars [{:?}]", &rp.1[0], st.chars);
                    }
                    *location += rp.4;
                    TailCall::Return(ParseReturn::Ok((st, rp.2.iappend(nodes))))
                },
                ParseReturn::Err(st) => {
                    if debug{
                        println!("parse_or, or_one [{:?}] none chars [{:?}]", &rp.1[0], st.chars);
                    }
                    TailCall::Call((rp.0, &rp.1[1..], rp.2, rp.3, rp.4))
                },
            }
        }
    })
}
fn parse_not<'a,'b,'c>(status: Status<'a>, expression: &'b Expression, location: &'c mut usize, debug: bool)
        ->ParseReturn<'a>{
    let mut tmp = 0;

    match parse_expr(status.clone(), expression, &mut tmp, debug){
        ParseReturn::Ok((mut st, nodes)) => {
            st.possion_bak(tmp);
            return ParseReturn::Err(st);
        },
        ParseReturn::Err(st) => {
            return ParseReturn::Ok((st,vec![]));
        },
    }
}
fn parse_atom_as_expr<'a,'b,'c>(status: Status<'a>, atom: &'b Atom, location: &'c mut usize, debug: bool)
        ->ParseReturn<'a>{
    return parse_atom(status, atom, location, debug);
}
fn parse_repeat<'a,'b,'c>(status: Status<'a>, rep_info: &'b RepInfo, location: &'c mut usize, debug: bool)
        ->ParseReturn<'a>{
    let init: (Status, usize, &RepInfo, Vec<Ast>, bool) =
        (status, 0, &rep_info, vec![], debug);

    if debug{
        println!("parse_repeat, repinfo [{:?}] status [{:?}]", init.2.expression, init.0.chars);
    }

    let mut tmp_location = 0;
    tail_call(init, |mut rp| {

        if let Some(ref end) = rp.2.end{

            let mut tmp_end_location = 0;
            match parse_expr(rp.0.clone(), end, &mut tmp_end_location, rp.4){
                ParseReturn::Ok((mut st, nodes)) => {

                    if debug{
                        println!("parse_repeat, repinfo [{:?}] end status [{:?}]", end, rp.0.chars);
                    }
                    st.possion_bak(tmp_end_location);

                    if let Some(min) = rp.2.min{
                        if rp.1 < min{
                            st.possion_bak(tmp_location);
                            return TailCall::Return(ParseReturn::Err(st));
                        }else{
                            *location += tmp_location;
                            return TailCall::Return(ParseReturn::Ok((st, rp.3)));
                        }
                    }else{
                        *location += tmp_location;
                        return TailCall::Return(ParseReturn::Ok((st, rp.3)));
                    }
                },
                ParseReturn::Err(st) => {},
            }
        }

        match parse_expr(rp.0.clone(), &rp.2.expression, &mut tmp_location, rp.4) {
            ParseReturn::Ok((st, nodes)) => {

                if let Some(max) = rep_info.max {
                    if (rp.1 + 1) >= max {
                        *location += tmp_location;
                        if debug{
                            println!("parse_repeat, repinfo [{:?}] end status [{:?}]", rp.2.expression, st.chars);
                        }
                        return TailCall::Return(ParseReturn::Ok((st, rp.3.iappend(nodes))));
                    }
                }

                if debug{
                    println!("parse_repeat, repinfo [{:?}] ok status [{:?}]", rp.2.expression, st.chars);
                }
                return TailCall::Call((st, rp.1 + 1, rp.2, rp.3.iappend(nodes), rp.4));
            },
            ParseReturn::Err(st) => {

                if debug{
                    println!("parse_repeat, repinfo [{:?}] end status [{:?}]", rp.2.expression, st.chars);
                }

                if let Some(min) = rep_info.min{
                    if (rp.1) < min{
                        rp.0.possion_bak(tmp_location);

                        return TailCall::Return(ParseReturn::Err(rp.0));
                    }
                }

                *location += tmp_location;
                return TailCall::Return(ParseReturn::Ok((rp.0, rp.3)));
            }
        }
    })
}
